import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class PendingParticipants( db.Model ):
    wave_id = db.StringProperty()
    participants = db.StringProperty()
    added_date = db.DateTimeProperty( auto_now_add = True )
    #completed = db.BooleanProperty() #wanted for posterity?

class MainPage( webapp.RequestHandler ):
    def get( self ):

        callback = self.request.get( 'callback' )
        if self.request.get( 'get' ) is not None and self.request.get( 'get' ) == "1": #requesting a list of new sets
            result_sets = ''
            for pendingSet in PendingParticipants.all().filter( 'wave_id = ', self.request.get( 'waveid' ) ):
                result_sets += '{"waveid":"' + pendingSet.wave_id + '","participants":"' + pendingSet.participants + '"},'
                pendingSet.delete()
            if len( result_sets ) == 0:
                result = callback + '({"status":"OK"})'
            else:
                result = callback + '({"status":"NEW", "sets":[' + result_sets[0:-1] + "]})"
            self.response.out.write( result )

        else: #adding a new set to the list
            newPendingParticipants = PendingParticipants()
            newPendingParticipants.wave_id = self.request.get( 'waveid' )
            newPendingParticipants.participants = self.request.get( 'participants' )
            newPendingParticipants.put()
            self.response.out.write( callback + '({"status":"OK"})' )

application = webapp.WSGIApplication( 
                                     [( '/add-participants', MainPage )],
                                     debug = True )

def main():
    run_wsgi_app( application )

if __name__ == "__main__":
    main()
